package com.sky.controller.admin;


import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@Slf4j
@RequestMapping("/admin/dish")
public class DishController {

    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;

    @GetMapping("/page")
    public Result<PageResult> DishPage(DishPageQueryDTO dishPageQueryDTO) {
        log.info("分页查询参数为 : {}", dishPageQueryDTO);
        PageResult pageResult = dishService.pageSearch(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    @GetMapping("/{id}")
    public Result getDishById(@PathVariable Integer id) {
        log.info("分页查询参数为 : {}", id);
        DishVO dish = dishService.getDishById(id);
        return Result.success(dish);
    }

    @PostMapping
    public Result addDish(@RequestBody DishDTO dishDTO) throws Exception {
        log.info("添加参数为 : {}", dishDTO);

        String key = "dish:" + dishDTO.getCategoryId();
        //清除缓存
        clearCache(key);

        dishService.addDishWithFlavor(dishDTO);
        return Result.success();
    }

    @GetMapping("/list")
    public Result<List<DishVO>> dishList(Integer categoryId) {
        log.info("查询菜品分类,参数为: {}", categoryId);
        List<DishVO> dishes = dishService.categoryIdByList(categoryId);
        return Result.success(dishes);
    }

    @PostMapping("/status/{status}")
    public Result stopOrStartDish(@PathVariable Integer status, Long id) {
        //清除缓存
        clearCache("dish_*");
        log.info("起售或停售,参数为: {} {}", status, id);
        dishService.statusDish(status, id);
        return Result.success();
    }

    /**
     * 修改菜品
     * @param dishDTO
     * @return
     */
    @PutMapping
    public Result updateDishWithFlavors(@RequestBody DishDTO dishDTO) {
        log.info("修改菜品,参数为为: {}", dishDTO);
        //清除缓存
        clearCache("dish_*");

        dishService.updateDishWithFlavors(dishDTO);
        return Result.success();
    }

    @DeleteMapping
    public Result deleteDishes(@RequestParam("ids") List<Long> ids) {
        log.info("删除菜品,参数为为: {}", ids);
        dishService.deleteDishes(ids);
        return Result.success();
    }

    /**
     * 清理缓存数据
     * @param pattern
     */
    private void clearCache(String pattern) {
        Set key = redisTemplate.keys(pattern);
        redisTemplate.delete(key);

    }
}
